package zhh.tangbao.websocket.client.impl;

import cn.hutool.core.lang.Assert;
import org.springframework.stereotype.Component;
import zhh.tangbao.system.utils.ApplicationContextUtil;
import zhh.tangbao.user.cache.UserCache;
import zhh.tangbao.user.vo.UserVo;
import zhh.tangbao.websocket.WebSocketServiceType;
import zhh.tangbao.websocket.client.WebSocketClient;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * <p>
 *     售货机状态监控的websocket实现类，负责返回关于各个售货机的实时数据
 * </p>
 * @author 粥灰灰
 * <p>2023/4/20</p>
 */

@ServerEndpoint(value = "/websocket/machine/{token}/{key}")
@Component
public class MachineClient extends WebSocketClient {

    private final UserCache userCache = ApplicationContextUtil.getBean(UserCache.class);

    @OnOpen
    @Override
    public void onOpen(Session session, @PathParam("token") String token, @PathParam("key") String key) {
        UserVo loginData = userCache.getLoginData(token, key);
        Assert.notNull(loginData, "用户登录授权已过期");
        this.id = loginData.getId();
        this.session = session;
        addClient(WebSocketServiceType.MACHINE, this.id, this);
    }

    @OnClose
    @Override
    public void onClose() {
        removeClient(WebSocketServiceType.MACHINE, this.id);
    }

    @OnError
    @Override
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    @Override
    public void onMessage(String message) {
        System.out.println("消息服务，收到客户端消息：" + message);
    }
}
